<template>
  <div class="articledetail bg-hex-fff pb-120rpx">
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
      <div class="relative">
        <image class="pointer-events-none absolute left-0 right-0 top-0 w-100%"
               :src="`${cdnUrl}/imgs/detail/bg.png${imgVersion}`" mode="widthFix" />
        <div
          :style="{ paddingTop: `${searchBarTop}px` }"
          class="z-999 flex items-center pb-50rpx"
          @click.stop="goBack">
          <uni-icons type="back" size="28" />
          <text class="text-36rpx font-600">返回</text>
        </div>
      </div>
    </div>
    <!-- 视频详情 -->
    <div v-if="articleType===2" class="box-border overflow-hidden rounded-32rpx p-32rpx">
      <x-video videoId="myVideo" class="w-full rounded-32rpx" :src="articleDetailinfo.multiMedia" :progress="0.1" @longpress="downLoadVideo(articleDetailinfo.multiMedia)" />
      <!-- <video id="myVideo" class="w-full rounded-32rpx"
             :src="articleDetailinfo.multiMedia"
             controls
             autoplay
             @longpress="downLoadVideo(articleDetailinfo.multiMedia)" /> -->
    </div>
    <div class="p-30rpx">
      <div v-if="articleType !== 0" class="mb-42rpx mt-24rpx text-36rpx font-500 text-hex-333333">{{ articleDetailinfo.title }}</div>
      <div class="mb-32rpx flex justify-between">
        <div class="flex items-center">
          <div>
            <image class="mr-24rpx h-86rpx w-86rpx rounded-50%" :src="articleDetailinfo.avatarUrl
            " mode="scaleToFill" @click.stop="navTo(`/pages-square/my?userId=${articleDetailinfo.userId}`)" />
          </div>
          <div>
            <div class="text-28rpx text-hex-333333">{{ articleDetailinfo.nickname }}</div>
            <div class="text-24rpx text-hex-BDBDBD">{{ articleDetailinfo.createdAt }}</div>
          </div>
        </div>
        <div
          class="box-border h-50rpx min-w-112rpx border-1 rounded-12rpx border-solid text-center text-24rpx leading-50rpx"
          :class="{
            'btn-theme-bg': articleDetailinfo.isAttention === 0,
            'btn-normal-bg': articleDetailinfo.isAttention === 1,
          }"
          @click.stop="handleClickAtt(articleDetailinfo)">
          {{ articleDetailinfo.isAttention === 0?'关注':'已关注' }}
        </div>
      </div>
      <div class="mb-30rpx flex justify-between">
        <div
          class="border-1 border-hex-ff4d4e rounded-8rpx border-solid bg-hex-FEF6FF px-10rpx py-1rpx text-center text-20rpx leading-36rpx text-hex-FF4E4E">
          {{ articleDetailinfo.columnName }}
        </div>
        <div class="flex items-center text-26rpx text-hex-7C8699">
          <div class="mr-18rpx flex items-center">
            <image class="mr-8rpx h-38rpx w-38rpx" :src="`${cdnUrl}/imgs/detail/see.png${imgVersion}`" mode="scaleToFill" />
            {{ articleDetailinfo.readCount }}
          </div>
          <div class="mr-18rpx flex items-center text-26rpx text-hex-7C8699">
            <image class="mr-8rpx h-38rpx w-38rpx"
                   :src="`${cdnUrl}/svgicons/likefalse.svg${imgVersion}`" mode="scaleToFill" />
            {{ articleDetailinfo.likeCount }}
          </div>
        </div>
      </div>
      <div v-if="articleType !== 1" class="word-break mb-32rpx text-28rpx leading-1.7em text-hex-7C8699">
        {{ articleDetailinfo.content }}
      </div>
      <!-- 动态详情 -->
      <div v-if="articleType === 0 " class="flex flex-wrap">
        <div v-for="(item, index) in showImgsList"
             class="relative mr-3% mt-24rpx h-200rpx w-200rpx overflow-hidden rounded-16rpx">
          <image
            class="absolute left-50% top-50% h-200rpx w-200rpx rounded-16rpx"
            style="transform: translate(-50%, -50%);" :src="item" mode="aspectFill" @click="previewImage({ ...item, index })" />
        </div>
        <div v-if="isShowPreview">
          <q-preview-image :urls="showImgsList" :current-index="currentIndex" @close="closePreview" @downLoad="Download" />
        </div>
      </div>
      <!-- 文章详情 -->
      <div v-if="articleType === 1 " class="w-full">
        <div v-for="item in articleContent" class="w-full">
          <div v-if="item.type === 'text'" style="white-space: pre-line;" class="word-break text-28rpx leading-1.7em text-hex-7C8699">
            {{ item.content }}
          </div>
          <div v-if="item.type==='img'">
            <image class="mb-10rpx w-full rounded-30rpx"
                   :src="item.content"
                   mode="widthFix"
                   @click="previewImage(item)" />
          </div>
        </div>
        <div v-if="isShowPreview">
          <q-preview-image :urls="showImgsList" :current-index="currentIndex" @close="closePreview" @downLoad="Download" />
        </div>
      </div>
    </div>
    <!-- 下面部分 -->
    <div class="box-border p-30rpx">
      <!-- 推荐阅读 -->
      <div v-if="articleType !==0">
        <div class="mb-24rpx text-32rpx text-hex-333333">推荐阅读</div>
        <div v-for="item in recommendList"
             class="mb-40rpx box-border w-full flex rounded-32rpx p-24rpx"
             style="box-shadow: 0rpx 8rpx 12rpx 0rpx rgb(240 240 240 / 38%), 0rpx -8rpx 12rpx 0rpx rgb(240 240 240 / 42%)"
             @click="routerTo('/pages-square/articledetail', item)">
          <div>
            <image
              class="mr-24rpx h-192rpx w-184rpx rounded-16rpx"
              :src="item.coverImage"
              mode="scaleToFill"
            />
          </div>
          <div>
            <div class="oneline-multiLine pt-5rpx text-28rpx font-600 text-hex-333333">{{ item.title }}</div>
            <div class="multiLine-hiddle my-10rpx mb-22rpx w-410rpx text-24rpx text-hex-7C8699">{{ item.content }}</div>
            <div class="flex items-center justify-between">
              <div class="flex items-center text-24rpx text-hex-7C8699">
                <image class="mr-12rpx h-44rpx w-44rpx rounded-50%" :src="item.avatarUrl" mode="scaleToFill"
                       @click.stop="navTo(`/pages-square/my?userId=${item.userId}`)" />
                {{ item.nickname }}
              </div>
              <div class="text-24rpx text-hex-7c8699">{{ item.createAt }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 评论列表 -->
      <div class="mb-20rpx text-28rpx text-hex-000000">评论({{ commentCount }})</div>
      <div class="mb-40rpx flex">
        <image class="mr-24rpx h-60rpx w-60rpx rounded-50%" :src="user.avatar_url" mode="scaleToFill" />
        <div class="relative mr-32rpx h-60rpx flex-1" @click="enableComment">
          <input
            disabled="true"
            class="box-border h-60rpx w-100% rounded-62rpx bg-hex-F3F3F3 pl-24rpx text-24rpx"
            type="text"
            placeholder="快来评论ta~">
          <image class="absolute right-24rpx top-9rpx z-99 h-42rpx w-42rpx"
                 :src="`${cdnUrl}/svgicons/inputimg.svg${imgVersion}`"
                 mode="scaleToFill" @click.stop="selectImg" />
        </div>
      </div>
      <!-- 展开回复 -->
      <div v-if="commentList && commentList.length >0">
        <div v-for="item in commentList" @click="opencommentpop(item)">
          <div class="mb-40rpx flex justify-between">
            <div class="flex items-center">
              <div>
                <image class="mr-20rpx h-60rpx w-60rpx rounded-30rpx" :src="item.avatarUrl" mode="scaleToFill"
                       @click.stop="navTo(`/pages-square/my?userId=${item.userId}`)" />
              </div>
              <div>
                <div class="mb-5rpx text-24rpx text-hex-7C8699">
                  {{ item.nickname }}
                  <text v-if="item.userId===userId" class="h-28rpx rounded-42rpx bg-hex-F5F5F5 px-8rpx text-center text-20rpx leading-28rpx">作者</text>
                </div>
                <div class="multiLine-hiddle more-multiLine text-24rpx">
                  {{ item.content.replace(/\s/g, '&nbsp;') }}
                  <text class="text-24rpx text-hex-7C8699">{{ formatMsgTime(item.createdAt) }}</text>
                <!-- <text class="text-24rpx text-hex-7C8699">{{ formatDayTime(item.createdAt) }}</text> -->
                </div>
              </div>
            </div>
            <div
              v-if="item.auditState ===0"
              class="h-36rpx min-w-88rpx border-1 border-hex-E499C2 rounded-8rpx border-solid bg-hex-FEF6FF pl-10rpx pr-10rpx text-center text-20rpx leading-36rpx text-hex-E499C2">
              审核中
            </div>
            <div v-if="item.auditState===1" class="flex items-center" @click.stop="handleCommendLike(item)">
              <image class="mr-5rpx h-38rpx w-38rpx"
                     :src="`${cdnUrl}/svgicons/like${item.isCommentLike?'true':'false'}.svg${imgVersion}`" mode="scaleToFill" />
              <text class="text-28rpx text-hex-7C8699">{{ item.likeCount }}</text>
            </div>
          </div>
          <div v-if="item.imageUrl" class="ml-80rpx">
            <image
              class="w-140rpx" :src="item.imageUrl" mode="widthFix"
            />
          </div>
          <div v-if="item.children">
            <!-- 后面的评论 -->
            <div v-if="item.isShowMore">
              <div v-for="item1 in item.children"
                   class="mb-40rpx ml-80rpx flex justify-between" @click.stop="opencommentpop(item1)">
                <div v-if="item1.userId===userId">
                  <div class="flex items-center">
                    <div>
                      <image class="mr-20rpx h-60rpx w-60rpx rounded-50%" :src="item1.avatarUrl" mode="scaleToFill"
                             @click.stop="navTo(`/pages-square/my?userId=${item.userId}`)" />
                    </div>
                    <div>
                      <div class="mb-5rpx text-24rpx text-hex-7C8699">
                        {{ item1.nickname }}
                        <text class="h-28rpx rounded-42rpx bg-hex-F5F5F5 px-8rpx text-center text-20rpx leading-28rpx">作者</text>
                        <text class="text-24rpx text-hex-7C8699"> {{ formatMsgTime(item1.createdAt) }} </text>
                      </div>
                      <div class="multiLine-hiddle more-multiLine w-80% text-24rpx">{{ item1.content.replace(/\s/g, '&nbsp;') }} </div>
                    </div>
                  </div>
                  <div v-if="item1.imageUrl" class="ml-80rpx pt-10rpx">
                    <image
                      class="w-140rpx" :src="item1.imageUrl" mode="widthFix"
                    />
                  </div>
                </div>
                <div v-else>
                  <div class="flex items-center">
                    <div>
                      <image class="mr-20rpx h-60rpx w-60rpx rounded-50%" :src="item1.avatarUrl" mode="scaleToFill"
                             @click.stop="navTo(`/pages-square/my?userId=${item.userId}`)" />
                    </div>
                    <div>
                      <div class="mb-5rpx text-24rpx text-hex-7C8699">
                        {{ item1.nickname }}
                      </div>
                    </div>
                  </div>
                  <div class="ml-60rpx text-24rpx">
                    <text class="multiLine-hiddle more-multiLine w-100% text-24rpx text-hex-7C8699">
                      <text class="text-hex-333">回复</text> {{ item1.replyNickname }}</text>
                    {{ item1.content }} <text class="text-24rpx text-hex-7C8699"> {{ formatMsgTime(item1.createdAt) }} </text>
                  </div>
                  <div v-if="item1.imageUrl" class="ml-80rpx pt-10rpx">
                    <image
                      class="w-140rpx" :src="item1.imageUrl" mode="widthFix"
                    />
                  </div>
                </div>
                <!-- <div
            class="h-36rpx border-1 border-hex-E499C2 rounded-8rpx border-solid bg-hex-FEF6FF pl-10rpx pr-10rpx text-center text-20rpx leading-36rpx text-hex-E499C2">
            审核中
          </div> -->
                <div class="flex items-center" @click.stop="handleCommendLike(item1)">
                  <image class="mr-5rpx h-38rpx w-38rpx"
                         :src="`${cdnUrl}/svgicons/like${item1.isCommentLike?'true':'false'}.svg${imgVersion}`" mode="scaleToFill" />
                  <text class="text-28rpx text-hex-7C8699">{{ item1.likeCount }}</text>
                </div>
              </div>
            </div>
            <!-- 展开3回复 -->
            <div class="mb-40rpx ml-160rpx text-24rpx text-hex-ABCD03" @click.stop="item.isShowMore = !item.isShowMore">{{ item.isShowMore?'收起回复':`展开${item.children.length}回复` }}</div>
            <!-- 收起回复 -->
            <!-- <div class="mb-40rpx ml-160rpx text-24rpx text-hex-ABCD03">收起回复</div> -->
          </div>
        </div>
        <div class="text-center text-24rpx text-hex-CECECE">—— 我是有底线的~ ——</div>
      </div>
      <!-- 暂无评论 -->
      <div v-else class="flex flex-col items-center">
        <div>
          <image class="h-364rpx w-364rpx" :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`" mode="scaleToFill" />
        </div>
        <div class="text-28rpx text-hex-7C8699">暂无评论</div>
      </div>
    </div>
    <div class="fixed bottom-0 left-0 right-0 z-99 box-border flex items-center justify-between bg-hex-ffffff p-30rpx pb-50rpx">
      <div class="relative mr-20rpx h-60rpx w-full" @click="enableComment">
        <input id="inputFocus" class="box-border h-60rpx w-full rounded-62rpx bg-hex-F3F3F3 pl-20rpx text-24rpx"
               disabled="true"
               type="text"
               placeholder="快来评论ta~">
        <image class="absolute right-24rpx top-9rpx z-99 h-42rpx w-42rpx"
               :src="`${cdnUrl}/svgicons/inputimg.svg${imgVersion}`" mode="scaleToFill"
               @click.stop="selectImg" />
      </div>
      <div class="flex items-center justify-around">
        <image class="mr-32rpx h-60rpx w-60rpx" :src="`${cdnUrl}/svgicons/pl_like${isLike ?'true':'false'}.svg${imgVersion}`"
               alt="" @click.stop="handleClickLike(articleDetailinfo)" />
        <image class="mr-32rpx h-60rpx w-60rpx" :src="`${cdnUrl}/svgicons/pl_save${isCollect ?'true':'false'}.svg${imgVersion}`"
               alt="" @click.stop="handleClickCollect(articleDetailinfo)" />
        <image class="h-60rpx w-60rpx" :src="`${cdnUrl}/svgicons/pl_share.svg${imgVersion}`" mode="scaleToFill" @click="opensharepop" />
      </div>
    </div>
    <!-- 分享弹窗 -->
    <uni-popup ref="sharepop" type="bottom" background-color="#fff" class="z-999">
      <go-share class="z-99999" @close="closepop" />
    </uni-popup>
    <uni-popup ref="codepopup" background-color="#fff" class="z-999 rounded-24rpx">
      <div class="rounded-24rpx">
        <div class="h-400rpx w-400rpx flex items-center justify-center bg-transparent">
          <image
            :src="wxQrcode"
            mode="scaleToFill"
            class="h-300rpx w-300rpx"
            @longpress="saveAlbum"
          />
        </div>
        <div class="flex items-center justify-center pb-32rpx">
          <div class="h-68rpx w-300rpx rounded-46rpx bg-hex-ABCD03 text-center text-28rpx leading-68rpx text-hex-fff"
          >长按图片保存</div>
        </div>
      </div>
    </uni-popup>
    <!-- 删除弹窗 -->
    <uni-popup ref="delpop">
      <div class="relative h-550rpx w-548rpx overflow-hidden rounded-30rpx">
        <div class="h-92rpx" />
        <div class="h-480rpx w-548rpx">
          <image class="mt--92rpx h-full w-548rpx" :src="`${cdnUrl}/imgs/detail/deletebg.png${imgVersion}`" mode="scaleToFill" />
          <div class="absolute left-0 right-0 top-20rpx text-center">
            <div class="mb-12% mt-43% text-36rpx font-bold text-hex-333333">删除这条评论?</div>
            <div class="mb-40rpx flex justify-around bg-hex-ffffff">
              <div class="h-68rpx w-182rpx border-1 border-hex-ABCD03 rounded-16rpx border-solid bg-hex-ffffff text-28rpx leading-68rpx text-hex-ABCD03" @click="closedelpop">取消</div>
              <div class="h-68rpx w-182rpx rounded-16rpx from-hex-ABCD03 to-hex-AFF6BE bg-gradient-to-b text-center text-28rpx leading-68rpx text-hex-ffffff" @click="deleteComment">确认</div>
            </div>
          </div>
        </div>
      </div>
    </uni-popup>
    <!-- 评论弹窗 -->
    <uni-popup ref="replypop" type="bottom" background-color="#fff">
      <div class="fixed left-0 z-999 w-full flex flex justify-center bg-hex-ffffff" :style="`bottom:${KeyboardHeight}px`">
        <div class="relative box-border h-92rpx flex-1 bg-hex-ffffff px-32rpx py-16rpx pr-20rpx">
          <div class="h-60rpx w-full flex items-center justify-between rounded-62rpx bg-hex-F3F3F3 pr-24rpx">
            <input v-model="content"
                   :focus="isFocus"
                   :adjust-position="false" :show-confirm-bar="false"
                   class="box-border h-60rpx flex-1 rounded-62rpx bg-hex-F3F3F3 pl-24rpx text-24rpx"
                   type="text" :placeholder="replyUser===''?'快来评论ta~':`回复给${replyUser}`">
            <image class="ml-24rpx h-60rpx w-60rpx"
                   :src="`${cdnUrl}/svgicons/inputimg.svg${imgVersion}`" mode="scaleToFill"
                   @click.stop="selectImg" />
          </div>
        </div>
        <div class="relative ml-36rpx box-border h-92rpx w-100rpx bg-hex-ffffff py-16rpx" @click.stop="publishComment">
          <div class="h-60rpx w-94rpx rounded-60rpx bg-hex-ABCD03 text-center text-24rpx leading-60rpx text-hex-ffffff">发送</div>
        </div>
      </div>
    </uni-popup>
    <!-- 评论的操作 -->
    <uni-popup ref="commentpop" background-color="#fff">
      <div class="z-9999 box-border h-360rpx rounded-tl-24rpx rounded-tr-24rpx bg-hex-ffffff p-50rpx">
        <div
          v-for="item in commetList"
          :key="item.id" class="h-100rpx border-b-2 text-center leading-100rpx"
          @click="item.handelevent">{{ item.text }}</div>
      </div>
    </uni-popup>
  </div>
</template>

<script setup lang="ts">
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

import { useUserStore } from '@/stores/user'

//关注
import { useLoginStore } from '@/stores/login'

const loginStore = useLoginStore()
const { user, useGetInfoData } = useUserStore()
let articleId: any = $ref('')
let articleType: any = $ref() //文章详情的类型
let searchBarTop: any = $ref('24')
let isShowShare = $ref(false)
let KeyboardHeight = $ref(0)
onLoad((options) => {
  // #ifndef H5
  /* let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top */
  // #endif
  if (options) {
    if (options.scene) {
      articleId = options.scene
      uni.setStorageSync('pageScene', `/pages-square/articledetail?articleId=${articleId}`)
    } else {
      articleId = options.articleId
      isShowShare = options?.showShare
    }
  }
})
onShareAppMessage((res) =>
{
  closepop()
  return {
    title: '心悦',
    path: `/pages-square/articledetail?scene=${articleId}`,
  }
})
onShareTimeline(() =>
{
  return {
    title: '分享朋友圈',
    query: `scene=${articleId}`,
  }
})
let articleDetailinfo: any = $ref({})
let articleContent: any = $ref([])
let recommendList: any = $ref([])
let showImgsList: any = $ref([])
let userId: any = $ref('')
const getArticleDetail = async () => {
  const { data, status, error } = await Fetch(`/qqyapi/auth/article/articleDetail/${articleId}`)
  // const { data, code, msg } = data
  if (data.code === 0) {
    articleDetailinfo = data.result
    showImgsList = (data.result?.multiMedia).split(',')
    articleType = data.result.articleType
    isLike = Boolean(articleDetailinfo.isLike)
    isCollect = Boolean(articleDetailinfo.isCollect)
    recommendList = data.result.recommendList
    recommendList.forEach((item) => {
      if (item.articleType === 1) {
        let jsonContent = JSON.parse(item.content)
        item.content = jsonContent[0].content
      }
    })
    userId = data.result.userId
    if (articleType === 1) {
      articleContent = JSON.parse(articleDetailinfo.content)
    }
  }
}
const routerTo = (route, item) => {
  navTo(`${route}?articleId=${item.id}&key=${Date.now()}`)
}
//关注
const handleClickAtt = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'userId': item.userId,
    },
  }
  switch (item.isAttention) {
    case 0:
      await Fetch('/qqyapi/auth/attention/addAttention', reqData).then(res => {
        if (res.status === 200) {
          articleDetailinfo.isAttention = 1
          useGetInfoData()
        }
      })
      break
    case 1:
      await Fetch('/qqyapi/auth/attention/cancelAttention', reqData).then(res => {
        if (res.status === 200) {
          articleDetailinfo.isAttention = 0
          useGetInfoData()
        }
      })
      break
  }
}
let isLike = $ref(false) //是否点赞
let isCollect = $ref(false) //是否收藏
//推荐列表：收藏,取消收藏
const handleClickCollect = useThrottleFn(async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (isCollect) {
    case false:
      await Fetch('/qqyapi/auth/collect/addCollect', reqData).then(res => {
        if (res.status === 200) {
          isCollect = true
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/collect/cancelCollect', reqData).then(res => {
        if (res.status === 200) {
          isCollect = false
        }
      })
      break
  }
}, 500)
//点赞,取消点赞
const handleClickLike = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'articleId': item.id,
    },
  }
  switch (isLike) {
    case false:
      await Fetch('/qqyapi/auth/article/like/addLike', reqData).then(res => {
        if (res.status === 200) {
          isLike = true
          articleDetailinfo.likeCount += 1
        }
      })
      break
    case true:
      await Fetch('/qqyapi/auth/article/like/cancelLike', reqData).then(res => {
        if (res.status === 200) {
          isLike = false
          articleDetailinfo.likeCount -= 1
        }
      })
      break
  }
}
//评论点赞,取消评论点赞
const handleCommendLike = async (item) => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      'commentId': item.id,
    },
  }
  switch (item.isCommentLike) {
    case 0:
      await Fetch('/qqyapi/auth/comment/like/addLike', reqData).then(res => {
        if (res.status === 200) {
          commentData.forEach((curItem) => {
            if (curItem.id === item.id) {
              curItem.isCommentLike = 1
              curItem.likeCount += 1
            }
          })
          formatdataList(commentData)
        }
      })
      break
    case 1:
      await Fetch('/qqyapi/auth/comment/like/cancelLike', reqData).then(res => {
        if (res.status === 200) {
          commentData.forEach((curItem) => {
            if (curItem.id === item.id) {
              curItem.isCommentLike = 0
              curItem.likeCount -= 1
            }
          })
          formatdataList(commentData)
        }
      })
      break
  }
}
//评论具体某一条
let content = $ref('')
let pid = $ref('')
let replyUser = $ref('')
let imageUrl = $ref('')
const publishComment = async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  if (!imageUrl && /^\s*$/.test(content)) {
    uni.showToast({
      title: '评论内容不能为空',
      icon: 'none',
    })
    return
  }
  const reqData = {
    method: 'post',
    data: {
      articleId,
      content,
      imageUrl,
      pid,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/comment/addComment', reqData)
  if (data.code === 0) {
    pid = ''
    content = ''
    replyUser = ''
    imageUrl = ''
    getcommentList(articleId)
    replypop.close()
  }
}
//删除某一条评论
const deleteComment = async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  const reqData = {
    method: 'post',
    data: {
      commentId: pid,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/auth/comment/deleteComment', reqData)
  if (data.code === 0) {
    getcommentList(articleId)
    closedelpop()
  }
}
//评论
onMounted(() => {
  /* uni.onKeyboardHeightChange(res => {
    KeyboardHeight = res.height
  }) */
  getArticleDetail()
  getcommentList(articleId)
  getShortLink()
  getQrcode()
  if (isShowShare) {
    opensharepop()
  }
})
let commentpop: any = $ref('')
// 评论
let replypop: any = $ref('')
let isFocus = $ref(false)
const enableComment = () => {
  replyUser = ''
  openreplypop()
}
const openreplypop = () => {
  isFocus = false //每次都要初始化变量，否则不生效
  setTimeout(() => {
    isFocus = true
  }, 100)
  replypop.open('bottom')
  commentpop.close()
}
//发图片
let fileLists: any = $ref([])
const selectImg = async () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  await chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    async success(res: any) {
      for (let i = 0; i < res.tempFiles.length; i++) {
        const fileUrl = await uploadCosFile(res.tempFiles[i], res.tempFiles[i].path)
        imageUrl = fileUrl
      }
      publishComment()
    },
  })
}
// 删除弹窗
const delpop: any = $ref('')
const opendelpop = () => {
  delpop.open('center')
  commentpop.close()
}
const closedelpop = () => {
  delpop.close()
}
const opencommentpop = (item) => {
  pid = item.id
  replyUser = item.nickname
  commentpop.open('bottom')
}
const closecommentpop = () => {
  pid = ''
  replyUser = ''
  commentpop.close()
}
const commetList = $ref([
  { id: '1', text: '回复', handelevent: openreplypop },
  { id: '2', text: '删除', handelevent: opendelpop },
  { id: '3', text: '取消', handelevent: closecommentpop },
])
const goBack = () => {
  uni.navigateBack({
    delta: 1,
  })
}
let isShowPreview = $ref(false)
let currentIndex = $ref(1) //预览图片位置
const previewImage = (item) => { // index 索引 如果 需要复用方法 可以使用 类型来进行区分(val)
  currentIndex = item.index
  isShowPreview = true
}
const closePreview = () => {
  isShowPreview = false
}
//下载图片
const Download = (link) => {
  console.log(link, '--------------')
  uni.downloadFile({
    url: link, //下载地址接口返回
    success: (data) => {
      if (data.statusCode === 200) {
        //文件保存到本地
        uni.saveImageToPhotosAlbum({
          filePath: data.tempFilePath,
          success() {
            uni.showToast({
              title: '图片已保存至本地',
              icon: 'none',
            })
          },
          fail() {
            uni.showToast({
              title: '保存失败',
              icon: 'none',
            })
          },
        })
      }
    },
    fail: (err) => {
      console.log(err)
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '失败请重新下载',
      })
    },
  })
}
//下载视频
const downLoadVideo = (link) => {
  uni.downloadFile({
    url: link, //下载地址接口返回
    success: (data) => {
      if (data.statusCode === 200) {
        //文件保存到本地
        uni.saveVideoToPhotosAlbum({
          filePath: data.tempFilePath,
          success() {
            uni.showToast({
              title: '视频已保存至本地',
              icon: 'none',
              duration: 2000,
            })
          },
          fail(err) {
            console.log('fail============', err)
            uni.showToast({
              title: '保存失败',
              icon: 'none',
              duration: 2000,
            })
          },
        })
      }
    },
    fail: (err) => {
      console.log(err)
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '失败请重新下载',
      })
    },
  })
}
// 分享弹窗
const sharepop: any = $ref(null)
const opensharepop = () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  sharepop.open('bottom')
}
const closepop = () => {
  sharepop.close()
}
//获取小程序码
let wxQrcode = $ref('')
const getQrcode = async () => {
  const reqData = {
    method: 'post',
    data: {
      'page': 'pages-square/articledetail',
      'scene': articleId,
      'check_path': false,
      'env_version': envVersion,
    },
  }
  const { data, status, error } = await Fetch('/api/wx/getwxacode', reqData)
  if (status === 200 && data.code === 0) {
    wxQrcode = data.result
  }
}
const codepopup: any = $ref(null)
const openCodePopup = () => {
  if (codepopup) {
    codepopup.open('center')
  }
}
let shortLink = $ref('')
const getShortLink = async () => {
  const reqData = {
    method: 'post',
    data: {
      'path': '/pages-square/articledetail',
      'query': `articleId=${articleId}`,
    },
  }
  const { data, status, error } = await Fetch('/api/wx/genwxaurllink', reqData)
  if (status === 200 && data.code === 0) {
    shortLink = data.result
  }
}
const copy = () => {
  uni.setClipboardData({
    data: shortLink,
    success() {
      uni.showToast({ title: '已复制', icon: 'none', duration: 2000 })
    },
  })
}
watchEffect(() => {
  uni.$on('openCode', () => {
    openCodePopup()
  })
  uni.$on('copylick', () => {
    copy()
  })
})
const saveAlbum = () => {
  uni.getSetting({ //获取用户的当前设置
    success: (res) => {
      if (res.authSetting['scope.writePhotosAlbum']) {//验证用户是否授权可以访问相册
        downLoadCode()
      } else {
        uni.authorize({ //如果没有授权，向用户发起请求
          scope: 'scope.writePhotosAlbum',
          success: () => {
            downLoadCode()
          },
          fail: () => {
            uni.showModal({
              content: '检测到您没打开保存图片的权限，是否去设置打开？',
              confirmText: '确认',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting({
                    success: (res) => {
                      // this.getLocation();
                    },
                  })
                } else {
                  console.log('取消')
                  return false
                }
              },
            })
            setTimeout(() => {
              uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
                success: (res2) => {
                  // console.log(res2.authSetting)
                },
              })
            }, 3000)
          },
        })
      }
    },
  })
}
const downLoadCode = () => {
  let base64 = wxQrcode.replace(/^data:image\/\w+;base64,/, '')//去掉data:image/png;base64,
  let name = 'wx.env.USER_DATA_PATH'
  let number = Math.random() * 10
  let filePath = `${name}/img${number}.png${imgVersion}`
  uni.getFileSystemManager().writeFile({
    filePath, //创建一个临时文件名
    data: base64, //写入的文本或二进制数据
    encoding: 'base64', //写入当前文件的字符编码
    success: res => {
      uni.saveImageToPhotosAlbum({
        filePath,
        success(res2) {
          codepopup.close()
          uni.showToast({
            title: '已保存至本地',
            icon: 'none',
            duration: 2000,
          })
        },
        fail() {
          codepopup.close()
          uni.showToast({
            title: '取消保存',
            icon: 'error',
            duration: 2000,
          })
        },
      })
    },
    fail: (err) => {
      codepopup.close()
      console.log(err, '--------------------')
    },
  })
}
// 评论列表
let commentList: any = $ref([])
let commentCount: any = $ref('')
const formatdataList = (list) => {
  commentList = flatToTree(list, { parentId: 'pid' })
  commentList.forEach(item => {
    item.isShowMore = false
    if (item.children) {
      item.children = treeToFlat(item.children, 'children')
    }
  })
}
let commentData: any = $ref([])
const getcommentList = async (articleId) => {
  const { data, status } = await Fetch(`/qqyapi/auth/comment/articleCommentPageList/${articleId}`)
  if (status === 200) {
    if (data.code === 0) {
      commentData = data.result?.commentList
      formatdataList(commentData)
      commentCount = data.result?.commentCount
    }
  }
}
</script>

<style lang="scss">
.articledetail{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break:break-all;
  }

  .word-break{
    word-break:break-all;
  }

  .more-multiLine{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 6;
    -webkit-box-orient: vertical;
    word-break:break-all;
  }

  .oneline-multiLine{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break:break-all;
  }

  ::v-deep(.uni-popup .uni-popup__wrapper) {
    display: block;
    position: relative;
    border-radius: 24rpx;
  }

  /* ::v-deep .is-input-border{
    border: none;
  }

  ::v-deep .uni-easyinput__content-input{
    height: 60rpx;
    background-color: #F3F3F3;
    border-radius: 62rpx;
  } */
}
</style>
